﻿using System.Diagnostics;
using System.Linq;
using System.Windows.Threading;

using VSTalk.Model;
using VSTalk.Tools;

using agsXMPP;
using agsXMPP.protocol.iq.roster;

namespace VSTalk.Engine.Core.XmppConnection.RosterObserver
{
    public class RosterObesrver : IListener
    {
        private readonly XmppClientConnection _connection;

        private readonly Dispatcher _dispatcher;

        private IActionWrapper<object> _onRosterStart;
        private IActionWrapper<object, RosterItem> _onRosterItem;
        private IActionWrapper<object> _onRosterEnd;

        private RosterListHandler _listHandler;
        private RosterItemHandler _itemHandler;
        private bool _listModeOn;

        public RosterObesrver(Client client, XmppClientConnection connection)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;
            _connection = connection;
            _listHandler = new RosterListHandler(client);
            _itemHandler = new RosterItemHandler(client);
        }


        public void StartListen()
        {
            _onRosterStart = _dispatcher.Wrap<object>(OnRosterStart);
            _connection.OnRosterStart += _onRosterStart.Exec;

            _onRosterItem = _dispatcher.Wrap<object, RosterItem>(OnRosterItem);
            _connection.OnRosterItem += _onRosterItem.Exec;

            _onRosterEnd = _dispatcher.Wrap<object>(OnRosterEnd);
            _connection.OnRosterEnd += _onRosterEnd.Exec;
        }

        public void StopListen()
        {
            _connection.OnRosterStart -= _onRosterStart.Exec;
            _connection.OnRosterItem -= _onRosterItem.Exec;
            _connection.OnRosterEnd -= _onRosterEnd.Exec;
        }

        private void OnRosterStart(object sender)
        {
            Debug.WriteLine("Reciving Roster " + _connection.MyJID);
            _listModeOn = true;
            _listHandler.Start();
        }

        private void OnRosterItem(object sender, RosterItem item)
        {
            if (_listModeOn)
            {
                _listHandler.OnRoster(item);
            }
            else
            {
                _itemHandler.OnRoster(item);
            }
        }

        private void OnRosterEnd(object sender)
        {
            _listHandler.Stop();
            _listModeOn = false;
            Debug.WriteLine("Roster recived " + _connection.MyJID);
        }
    }
}